package com.dove.tcpserver;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Main2Activity extends AppCompatActivity {

    private ServerSocket serverSocket;
    private Socket clientSocket;
    private InputStream is;
    private InputStreamReader isr;
    private BufferedReader br;
    private OutputStream os;
    private PrintWriter pw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        new Thread(runnable).start();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            TCPServer();
        }
    };

    protected void TCPServer(){
        try {
            //创建服务器端 Socket，指定监听端口
            serverSocket = new ServerSocket(8888);
            //等待客户端连接
            Log.i("dove","等待客户端连接");
            clientSocket = serverSocket.accept();
            Log.i("dove","获取客户端输入流");
            //获取客户端输入流，
            is = clientSocket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String data = null;
            //读取客户端数据
            while((data = br.readLine()) != null){
                Log.i("dove","服务器接收到客户端的数据：" + data);
            }

            //获取客户端输出流
            os = clientSocket.getOutputStream();
            pw = new PrintWriter(os);
            //向客户端发送数据
            pw.print("我是服务端");
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            //关闭输入流
            clientSocket.shutdownInput();
            //关闭输出流
            clientSocket.shutdownOutput();
            //关闭资源
            pw.checkError();
            os.close();
            br.close();
            isr.close();
            is.close();
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
